<?php

namespace App\Process;

use App\Model\WechatsCustomModel;
use App\Utility\Cache;
use App\Utility\CacheDatas;
use App\Utility\MiniProgram;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\EasySwoole\Logger;

class MessageCustorm extends AbstractProcess
{
    private $isRun = false;
    public function run($arg){
        //定时500ms检测有没有任务，有的话就while死循环执行
        $this->addTick(200,function (){
            if(!$this->isRun){
                $this->isRun = true;
                go(function (){
                    while (true){
                        try{
                            $queue = new Cache();
                            $task = $queue->onQueue('message-custorm')->read();
                            if($task){
                                $custormModel = new WechatsCustomModel();
                                $kefuMsg = $custormModel->where('applet',$task['applet'])->inRandomOrder()->first();
                                if($kefuMsg){
                                    $sendData = [
                                        'type' => 'link',
                                        'openid' => $task['openid'],//用户OPENID
                                        'title' => $kefuMsg['title'],//消息标题
                                        'description' => $kefuMsg['description'],//消息描述
                                        'url' => $kefuMsg['url'],//链接地址
                                        'thumb_url' => $kefuMsg['thumb_url'],//图片地址
                                    ];
                                    $wechat = new MiniProgram($task['applet']);
                                    return $wechat->sendCustomerMessage($sendData);
                                }else{
                                    break;
                                }
                                unset($custormModel);
                            }else{
                                break;
                            }
                            unset($queue);
                        }catch (\Throwable $throwable){
                            break;
                        }
                    }
                    $this->isRun = false;
                });
                unset($queue);
            }
        });
    }

    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }

    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }
}
